<template>
    <div class="major-management-container">
        <div class="page-header">
            <h2 class="page-title">专业管理</h2>
            <div class="operation-group">
                <!-- 同步学生账号按钮 -->
                <el-button type="primary" icon="el-icon-refresh" @click="syncStudentAccount">同步学生账号</el-button>
                <el-upload
                    class="excel-uploader"
                    action=""
                    :show-file-list="false"
                    :before-upload="beforeExcelUpload"
                    accept=".xlsx,.xls">
                    <el-button type="success" icon="el-icon-upload2">导入学生信息</el-button>
                </el-upload>
                <el-button type="primary" icon="el-icon-plus" @click="handleAddMajor">新增专业</el-button>
            </div>
        </div>

        <!-- 搜索区域 -->
        <div class="search-container">
            <el-input placeholder="请输入专业名称或编号" v-model="searchQuery" clearable prefix-icon="el-icon-search"
                class="search-input"></el-input>
        </div>

        <!-- 专业列表表格 -->
        <el-table :data="filteredMajors" border style="width: 100%" v-loading="tableLoading"
            :header-cell-style="{ background: '#f5f7fa', color: '#606266' }">
            <el-table-column prop="id" label="序号" width="80" align="center"></el-table-column>
            <el-table-column prop="majorCode" label="专业编号" width="150"></el-table-column>
            <el-table-column prop="majorName" label="专业名称"></el-table-column>
            <el-table-column prop="number" label="录取人数" width="120" align="center"></el-table-column>
            <el-table-column label="操作" width="200" align="center">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEditMajor(scope.row)"
                        plain>编辑</el-button>
                    <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDeleteMajor(scope.row)"
                        plain>删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="filteredMajors.length"></el-pagination>
        </div>

        <!-- 新增/编辑专业对话框 -->
        <el-dialog :title="dialogType === 'add' ? '新增专业' : '编辑专业'" :visible.sync="dialogVisible" width="500px"
            :close-on-click-modal="false">
            <el-form :model="majorForm" :rules="rules" ref="majorForm" label-width="100px">
                <el-form-item label="专业编号" prop="code">
                    <el-input v-model="majorForm.code" placeholder="请输入专业编号"></el-input>
                </el-form-item>
                <el-form-item label="专业名称" prop="name">
                    <el-input v-model="majorForm.name" placeholder="请输入专业名称"></el-input>
                </el-form-item>
                <el-form-item label="录取人数" prop="quota">
                    <el-input-number v-model="majorForm.quota" :min="1" :max="500" controls-position="right"
                        style="width: 100%"></el-input-number>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitMajorForm" :loading="submitLoading">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: 'MajorManagement',
    data() {
        return {
            // 表格数据
            majors: [],
            // 表格加载状态
            tableLoading: false,
            // 搜索关键词
            searchQuery: '',
            // 分页
            currentPage: 1,
            pageSize: 10,
            // 对话框
            dialogVisible: false,
            dialogType: 'add', // 'add' 或 'edit'
            // 表单数据
            majorForm: {
                id: null,
                code: '',
                name: '',
                quota: 50
            },
            // 表单验证规则
            rules: {
                code: [
                    { required: true, message: '请输入专业编号', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                ],
                name: [
                    { required: true, message: '请输入专业名称', trigger: 'blur' },
                    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
                ],
                quota: [
                    { required: true, message: '请输入录取人数', trigger: 'blur' },
                    { type: 'number', min: 1, message: '录取人数必须大于0', trigger: 'blur' }
                ]
            },
            // 提交按钮加载状态
            submitLoading: false
        }
    },
    computed: {
        // 过滤后的专业列表
        filteredMajors() {
            if (!this.searchQuery) {
                return this.majors;
            }

            const query = this.searchQuery.toLowerCase();
            return this.majors.filter(major =>
                (major.majorName && major.majorName.toLowerCase().includes(query)) ||
                (major.majorCode && major.majorCode.toLowerCase().includes(query))
            );
        }
    },
    methods: {
        // 获取专业列表数据
        getMajorList() {
            this.tableLoading = true;
            this.$get('/api/majorDetails').then(res => {
                if (res.code === 200) {
                    this.majors = res.data;
                    this.$message.success('数据加载成功');
                } else {
                    this.$message.error('获取数据失败');
                }
            }).catch(err => {
                this.$message.error('获取数据失败');
                console.error(err);
            }).finally(() => {
                this.tableLoading = false;
            });
        },

        // 上传前校验
        beforeExcelUpload(file) {
            const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                            file.type === 'application/vnd.ms-excel';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isExcel) {
                this.$message.error('只能上传Excel文件!');
                return false;
            }
            if (!isLt2M) {
                this.$message.error('文件大小不能超过 2MB!');
                return false;
            }

            // 创建FormData对象
            const formData = new FormData();
            formData.append('file', file);

            // 发送上传请求
            this.$post('/api/studentInfo/upload', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            }).then(res => {
                if (res.code === 200) {
                    this.$message.success('导入成功');
                    this.getMajorList();
                } else {
                    this.$message.error(res.msg || '导入失败');
                }
            }).catch(() => {
                this.$message.error('导入失败');
            });

            return false; // 阻止自动上传
        },
        syncStudentAccount(){
            this.$get('/api/studentInfo/synchronization').then(res=>{
                if(res.code === 200){
                    this.$message.success('同步成功');
                }else{
                    this.$message.error(res.msg || '同步失败');
                }
            })
        },
        // 处理新增专业
        handleAddMajor() {
            this.dialogType = 'add';
            this.majorForm = {
                id: null,
                code: '',
                name: '',
                quota: 50
            };
            this.dialogVisible = true;
            // 在下一个事件循环中重置表单验证
            this.$nextTick(() => {
                this.$refs.majorForm && this.$refs.majorForm.clearValidate();
            });
        },

        // 处理编辑专业
        handleEditMajor(row) {
            this.dialogType = 'edit';
            // 将后端数据格式转换为表单数据格式
            this.majorForm = {
                id: row.id,
                code: row.majorCode,
                name: row.majorName,
                quota: row.number
            };
            this.dialogVisible = true;
            // 在下一个事件循环中重置表单验证
            this.$nextTick(() => {
                this.$refs.majorForm && this.$refs.majorForm.clearValidate();
            });
        },

        // 处理删除专业
        handleDeleteMajor(row) {
            this.$confirm(`确定要删除专业 "${row.majorName}" 吗？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // this.tableLoading = true;  // 取消注释，激活加载状态
                this.$delete(`/api/majorDetails/${row.id}`)
                    .then(res => {
                        if (res.code === 200) {
                            this.$message.success('删除成功');
                            this.getMajorList(); // 刷新列表数据
                        } else {
                            this.$message.error(res.msg || '删除失败');
                        }
                    })
                    .catch(err => {
                        console.error(err);
                        this.$message.error('删除失败');
                    })
                    .finally(() => {
                        this.tableLoading = false;
                    });
            }).catch(() => {
                // 取消删除操作，不做处理
            });
        },

        // 提交表单
        submitMajorForm() {
            this.$refs.majorForm.validate((valid) => {
                if (valid) {
                    this.submitLoading = true;
                    
                    const params = {
                        id: this.majorForm.id,
                        majorCode: this.majorForm.code,
                        majorName: this.majorForm.name, 
                        number: this.majorForm.quota
                    };

                    if (this.dialogType === 'add') {
                        // 添加专业
                        this.$post('/api/majorDetails', params)
                            .then(res => {
                                if (res.code === 200) {
                                    this.$message.success('添加成功');
                                    this.dialogVisible = false;
                                    this.getMajorList(); // 刷新列表
                                } else {
                                    this.$message.error(res.msg || '添加失败');
                                }
                            })
                            .catch(err => {
                                console.error(err);
                                this.$message.error('添加失败');
                            })
                            .finally(() => {
                                this.submitLoading = false;
                            });
                    } else {
                        // 编辑专业
                        this.$put('/api/majorDetails', params)
                            .then(res => {
                                if (res.code === 200) {
                                    this.$message.success('修改成功');
                                    this.dialogVisible = false;
                                    this.getMajorList(); // 刷新列表
                                } else {
                                    this.$message.error(res.msg || '修改失败');
                                }
                            })
                            .catch(err => {
                                console.error(err);
                                this.$message.error('修改失败');
                            })
                            .finally(() => {
                                this.submitLoading = false;
                            });
                    }
                } else {
                    return false;
                }
            });
        },

        // 处理每页显示数量变化
        handleSizeChange(val) {
            this.pageSize = val;
        },

        // 处理页码变化
        handleCurrentChange(val) {
            this.currentPage = val;
        }
    },
    created() {
        // 页面创建时获取数据
        this.getMajorList();
    }
}
</script>

<style scoped>
.major-management-container {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 120px);
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.page-title {
    font-size: 22px;
    font-weight: 600;
    color: #303133;
    margin: 0;
}

.operation-group {
    display: flex;
    gap: 10px;
}

.excel-uploader {
    display: inline-block;
}

.search-container {
    margin-bottom: 20px;
}

.search-input {
    width: 300px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

@media (max-width: 768px) {
    .page-header {
        flex-direction: column;
        align-items: flex-start;
    }

    .page-header .el-button {
        margin-top: 10px;
    }

    .search-input {
        width: 100%;
    }

    .pagination-container {
        justify-content: center;
    }
}
</style>